package com.cloud.async.business.body;

import com.cloud.async.util.ex.AsyncException;

/**
 * 创建任务结果返回
 *
 */
public class BusinessResult {

    /**
     * 类型信息
     */
    private final Class<?> responseType;

    /**
     * 错误信息（可选）
     */
    private final String errorMsg;

    /**
     *
     */
    private final String taskId;


    /**
     * 当前时间戳（毫秒）
     */
    private final long taskTimestamp;

    // 成功情况的构造函数
    public BusinessResult(String taskId, Class<?> responseType, long taskTimestamp) {
        this.taskId = taskId;
        this.errorMsg = null;
        this.responseType = responseType;
        this.taskTimestamp = taskTimestamp;
    }

    // 失败情况的构造函数
    public BusinessResult(String taskId, Class<?> responseType, long taskTimestamp, String errorMsg) {
        this.taskId = taskId;
        this.errorMsg = errorMsg;
        this.responseType = responseType;
        this.taskTimestamp = taskTimestamp;
    }


    /**
     * 获取成功的任务ID
     * @param async 异常类型（用于构造失败时的异常）
     * @return 成功时的taskId
     * @throws AsyncException 当任务失败时抛出指定类型的异常
     */
    public String getSuccessTaskId(Class<? extends AsyncException> async) throws AsyncException {
        if (isSuccess()) {
            return taskId;
        }

        // 失败情况：构造指定类型的异常并抛出
        try {
            // 通过反射创建异常实例，确保异常信息完整
            AsyncException exception = async.getDeclaredConstructor(String.class)
                    .newInstance(errorMsg != null ? errorMsg : "Unknown error occurred");
            throw exception;
        } catch (Exception e) {
            // 反射失败时降级处理，抛出默认异常
            throw new AsyncException("Failed to create custom exception: " + e.getMessage());
        }
    }

    public String getSuccessTaskId() throws AsyncException {
        if (isSuccess()) {
            return taskId;
        }
        throw new AsyncException(errorMsg != null ? errorMsg : "Business operation failed");
    }

    public String getTaskId() {
        return taskId;
    }

    public Class<?> getResponseType() {
        return responseType;
    }

    public long getTaskTimestamp() {
        return taskTimestamp;
    }

    public String getErrorMsg() {
        return errorMsg;
    }




    // 判断是否成功
    public boolean isSuccess() {
        return errorMsg == null || "".equals(errorMsg);
    }
}
